package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;

/**
 * User: Administrator
 * Date: 2021/4/13
 * Time: 10:51
 * Description:
 */
public class NioDiscardServer {
    public static void main(String[] args) throws IOException {
        // 1、获取选择器
        Selector selector = Selector.open();
        // 2、获取通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 3、设置非阻塞
        serverSocketChannel.configureBlocking(false);
        // 4、绑定连接
        serverSocketChannel.bind(new InetSocketAddress(9033));
        // 5、将io事件注册到选择器
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 6、轮询io就绪事件
        while (selector.select() > 0) {
            // 7、获取选择键集合
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                // 8、判断每个类型
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    // 9、可读事件注册到选择器
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 10、读取数据
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int length = 0;
                    while((length = channel.read(byteBuffer)) > 0) {
                        byteBuffer.flip();
                        System.out.println(Arrays.toString(byteBuffer.array()));
                        String s = Arrays.toString(byteBuffer.array());
                        Charset charset = Charset.forName("UTF-8");
                        CharsetDecoder decoder = charset.newDecoder();
                        String s1 = decoder.decode(byteBuffer.asReadOnlyBuffer()).toString();
                        System.out.println(s1);
                        byteBuffer.clear();
                    }
                    channel.close();
                }
                iterator.remove();
            }
        }
        serverSocketChannel.close();
    }

}
